/**
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY. See the GNU General Public License for more details. Copyright (C) 2011 CellObject.net
 */
package net.cellobject.sqlitexmlbrowser.sqlitebrowser.schema;

import java.util.List;
import java.util.Set;
import org.tmatesoft.sqljet.core.SqlJetException;
import org.tmatesoft.sqljet.core.schema.ISqlJetColumnDef;
import org.tmatesoft.sqljet.core.schema.ISqlJetIndexDef;
import org.tmatesoft.sqljet.core.schema.ISqlJetSchema;
import org.tmatesoft.sqljet.core.schema.ISqlJetTableDef;

public class SchemaTree {
	private final Object root;

	public static SchemaTree createInstance(final ISqlJetSchema schema) throws SqlJetException {
		SchemaTreeNode root = new SchemaTreeNode();
		if (schema == null) {
			return new SchemaTree(root);
		}
		try {
			final Set<String> tableNames = schema.getTableNames();
			for (final String tableName : tableNames) {
				final ISqlJetTableDef table = schema.getTable(tableName);
				final SchemaTreeNode node = new SchemaTreeNode(table);
				final List<ISqlJetColumnDef> columns = table.getColumns();
				for (final ISqlJetColumnDef column : columns) {
					node.addChild(new SchemaTreeNode(table, column));
				}
				root.addChild(node);
			}
			final Set<String> indexNames = schema.getIndexNames();
			for (final String indexName : indexNames) {
				final ISqlJetIndexDef index = schema.getIndex(indexName);
				root.addChild(new SchemaTreeNode(index));
			}
		} catch (final SqlJetException e) {
			root = new SchemaTreeNode();
			throw e;
		}
		return new SchemaTree(root);
	}

	private SchemaTree(final SchemaTreeNode root) {
		this.root = root;
	}

	public int getChildCount(final Object parent) {
		return ((SchemaTreeNode)parent).getChildCount();
	}

	public int getIndexOfChild(final Object parent, final Object child) {
		return ((SchemaTreeNode)parent).getIndexOfChild((SchemaTreeNode)child);
	}

	public Object getChild(final Object parent, final int index) {
		return ((SchemaTreeNode)parent).getChildAt(index);
	}

	public Object getRoot() {
		return root;
	}

	public boolean isLeaf(final Object node) {
		return ((SchemaTreeNode)node).isLeaf();
	}
}
